package bll

import (
	"context"
	"maya-service/store/mysql"

	"maya-service/model"
	"maya-service/model/entity"
	"maya-service/model/mapping"
	"maya-service/store"
	"time"
)

type userRecord struct {
	iUserRecord store.IUserRecord
}

var UserRecord = &userRecord{
	iUserRecord: mysql.UserRecord,
}

func init() {
	Register(UserRecord)
}

func (a *userRecord) init() func() {
	return func() {}
}

// Create
func (a *userRecord) Create(ctx context.Context, in *model.UserRecordCreateRequest) error {
	var (
		err error
	)
	c := buildUserRecord(in)
	_, err = a.iUserRecord.Create(ctx, c)
	return err
}

// Update
func (a *userRecord) Update(ctx context.Context, in *model.UserRecordUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	if in.UserId != nil {
		dict["user_id"] = in.UserId
	}

	if in.NickName != nil {
		dict["nick_name"] = in.NickName
	}

	if in.CustomData != nil {
		dict["custom_data"] = in.CustomData
	}

	if in.Supervisor != nil {
		dict["supervisor"] = in.Supervisor
	}

	if in.Phone != nil {
		dict["phone"] = in.Phone
	}

	if in.CreatedAt != nil {
		dict["created_at"] = in.CreatedAt
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	if in.Avatar != nil {
		dict["avatar"] = in.Avatar
	}

	if in.UserMoney != nil {
		dict["user_money"] = in.UserMoney
	}

	if in.WithdrawMoney != nil {
		dict["withdraw_money"] = in.WithdrawMoney
	}

	if in.WxwebOpenid != nil {
		dict["wxweb_openid"] = in.WxwebOpenid
	}

	// do other update here
	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt
	return a.iUserRecord.Update(ctx, *in.UserId, dict)
}

// Delete
func (a *userRecord) Delete(ctx context.Context, in *model.UserRecordDeleteRequest) error {
	return a.iUserRecord.Delete(ctx, in.Id)
}

// List
func (a *userRecord) List(ctx context.Context, in *model.UserRecordListRequest) (*model.UserRecordListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.UserRecord
		out   = &model.UserRecordListResponse{}
	)

	if total, list, err = a.iUserRecord.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = mapping.UserRecordsEntityToDto(list)

	return out, nil
}

// Find
func (a *userRecord) Find(ctx context.Context, in *model.UserRecordInfoRequest) (*model.UserRecordInfo, error) {
	var (
		err  error
		data *entity.UserRecord
		out  = &model.UserRecordInfo{}
	)

	if data, err = a.iUserRecord.Find(ctx, in); err != nil {
		return nil, err
	}

	out = mapping.UserRecordEntityToDto(data)
	return out, nil
}

// buildUserRecord build entity
func buildUserRecord(in *model.UserRecordCreateRequest) *entity.UserRecord {

	ety := &entity.UserRecord{}

	ety.UserId = in.UserId

	ety.CustomData = in.CustomData

	ety.Supervisor = in.Supervisor

	ety.UserMoney = in.UserMoney

	ety.WithdrawMoney = in.WithdrawMoney

	ety.CreatedAt = time.Now().Unix()

	ety.UpdatedAt = in.UpdatedAt

	return ety
}
